/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

MainPanel = function(){
	//Preview panel to show blog contents.
    this.preview = new Ext.Panel({
        id: 'preview',
        region: 'south',
        cls:'preview',
        autoScroll: true,
        listeners: FeedViewer.LinkInterceptor,

        tbar: [{
            id:'tab',
            text: 'View in New Tab',
            iconCls: 'new-tab',
            disabled:true,
            handler : this.openTab,
            scope: this
        },
        '-',
        {
            id:'win',
            text: 'See Original Post',
            iconCls: 'new-win',
            disabled:true,
            scope: this,
            handler : function(){
                window.open(this.gsm.getSelected().data.link);
            }
        }],

        clear: function(){
            this.body.update('');
            var items = this.topToolbar.items;
            items.get('tab').disable();
            items.get('win').disable();
        }
    });

    this.grid = new FeedGrid(this, {
        tbar:[{
            text:'Open All',
            tooltip: {title:'Open All',text:'Opens all item in tabs'},
            iconCls: 'tabs',
            handler: this.openAll,
            scope:this
        },
        '-',
        {
            split:true,
            text:'Reading Pane',
            tooltip: {title:'Reading Pane',text:'Show, move or hide the Reading Pane'},
            iconCls: 'preview-bottom',
            handler: this.movePreview.createDelegate(this, []),
            menu:{
                id:'reading-menu',
                cls:'reading-menu',
                width:100,
                items: [{
                    text:'Bottom',
                    checked:true,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-bottom'
                },{
                    text:'Right',
                    checked:false,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-right'
                },{
                    text:'Hide',
                    checked:false,
                    group:'rp-group',
                    checkHandler:this.movePreview,
                    scope:this,
                    iconCls:'preview-hide'
                }]
            }
        },
        /*'-',
        {
            pressed: true,
            enableToggle:true,
            text:'Summary',
            tooltip: {title:'Post Summary',text:'View a short summary of each item in the list'},
            iconCls: 'summary',
            scope:this,
            toggleHandler: function(btn, pressed){
                this.grid.togglePreview(pressed);
            }
        },*/
        '-',
        {
            text:'Create a new blog article',
            tooltips: {title:'Add a new entry', text:'Create a new blog article in a new tab'},
            iconCls: 'new-tab',
            scope: this,
            handler: this.createArticle
        },
        '-',
        {
            text:'Edit',
            tooltips: {title:'Edit Current Selected', text:'Edit currently selected blog'},
            iconCls: 'new-tab',
            scope: this,
            handler: this.editArticle
        },
        '-',
        {
            text:'Delete',
            tooltips: {title:'Delete Current Selected', text:'Delete currently selected blog'},
            iconCls: 'new-tab',
            scope: this,
            handler: this.deleteArticle
        }]
    });

    MainPanel.superclass.constructor.call(this, {
        id:'main-tabs',
        activeTab:0,
        region:'center',
        margins:'0 5 5 0',
        resizeTabs:true,
        tabWidth:150,
        minTabWidth: 120,
        enableTabScroll: true,
        plugins: new Ext.ux.TabCloseMenu(),
        items: {
            id:'main-view',
            layout:'border',
            title:'Loading...',
            hideMode:'offsets',
            items:[
                this.grid, {
                id:'bottom-preview',
                layout:'fit',
                items:this.preview,
                height: 250,
                split: true,
                border:false,
                region:'south'
            }, {
                id:'right-preview',
                layout:'fit',
                border:false,
                region:'east',
                width:350,
                split: true,
                hidden:true
            }]
        }
    });

    this.gsm = this.grid.getSelectionModel();
    
    //When a row in the feed grid is selected,
    //write preview contents to the preview body.
    this.gsm.on('rowselect', function(sm, index, record){
        FeedViewer.getTemplate().overwrite(this.preview.body, record.data);
        var items = this.preview.topToolbar.items;
        items.get('tab').enable();
        items.get('win').enable();
        
        
        // Add hover handler to the notes.
        var notes = Ext.query(".note-simple");
        
        
        for(var i=0; i< notes.length; i++){
        	var par = Ext.get(notes[i].parentNode);
        	var noteid = 0;
        	if(par.hasClass("note-holder")){
        		noteid = par.id;
        	}
        	new Ext.ToolTip({
                scope:this,
                target: Ext.get(notes[i]).id,
                width: 200,
                autoLoad: {url: 'GetNote?noteid=' + noteid},
                dismissDelay: 15000
            });
//            Ext.get(notes[i]).hover(
//                function(){
//                	
//                	
//                	// TODO: use panel to perform complex tasks.
//                	// TODO: get id.
////                    new Ext.ToolTip({
////                        target: 'ajax-tip',
////                        width: 200,
////                        autoLoad: {url: 'Note?noteid='+noteid},
////                        dismissDelay: 15000 // auto hide after 15 seconds
////                    });
//                },
//                function(){
//                },
//                this
//            );
        }
    }, this, {buffer:250});

    this.grid.store.on('beforeload', this.preview.clear, this.preview);
    this.grid.store.on('load', this.gsm.selectFirstRow, this.gsm);

    //Double click on grid to open preview in a new tab.
    this.grid.on('rowdblclick', this.openTab, this);
};

Ext.extend(MainPanel, Ext.TabPanel, {

    loadFeed : function(feed){
        this.grid.loadFeed(feed.url);
        Ext.getCmp('main-view').setTitle(feed.text);
    },
    

    movePreview : function(m, pressed){
        if(!m){ // cycle if not a menu item click
            var readMenu = Ext.menu.MenuMgr.get('reading-menu');
            readMenu.render();
            var items = readMenu.items.items;
            var b = items[0], r = items[1], h = items[2];
            if(b.checked){
                r.setChecked(true);
            }else if(r.checked){
                h.setChecked(true);
            }else if(h.checked){
                b.setChecked(true);
            }
            return;
        }
        if(pressed){
            var preview = this.preview;
            var right = Ext.getCmp('right-preview');
            var bot = Ext.getCmp('bottom-preview');
            var btn = this.grid.getTopToolbar().items.get(2);
            switch(m.text){
                case 'Bottom':
                    right.hide();
                    bot.add(preview);
                    bot.show();
                    bot.ownerCt.doLayout();
                    btn.setIconClass('preview-bottom');
                    break;
                case 'Right':
                    bot.hide();
                    right.add(preview);
                    right.show();
                    right.ownerCt.doLayout();
                    btn.setIconClass('preview-right');
                    break;
                case 'Hide':
                    preview.ownerCt.hide();
                    preview.ownerCt.ownerCt.doLayout();
                    btn.setIconClass('preview-hide');
                    break;
            }
        }
    },

    openTab : function(record){
        record = (record && record.data) ? record : this.gsm.getSelected();
        var d = record.data;
        var id = !d.link ? Ext.id() : d.link.replace(/[^A-Z0-9-_]/gi, '');
        var tab;
        if(!(tab = this.getItem(id))){
            tab = new Ext.Panel({
                id: id,
                cls:'preview single-preview',
                title: d.title,
                tabTip: d.title,
                html: FeedViewer.getTemplate().apply(d),
                closable:true,
                listeners: FeedViewer.LinkInterceptor,
                autoScroll:true,
                border:true,

                tbar: [{
                    text: 'Go to Original Post',
                    iconCls: 'new-win',
                    handler : function(){
                        window.open(d.link);
                    }
                }]
            });
            this.add(tab);
        }
        this.setActiveTab(tab);
    },

    openAll : function(){
        this.beginUpdate();
        this.grid.store.data.each(this.openTab, this);
        this.endUpdate();
    },
    
    createArticle: function() {
    	var newid = 'contenteditor'+Ext.id();
    	
    	var tab = new Ext.FormPanel({
    		id: 'my-details',
            labelAlign: 'top',
            frame:true,
            title: 'New Article',
            bodyStyle:'padding:5px 5px 0',
            width: 600,
            closable:true,
            
            
            buttons: [{
                text: 'Save',
                type: 'submit',
                scope: this,
                handler: function(){
                    tab.getForm().submit({
                        url:'CreateArticle', 
                        waitMsg:'Saving Article...',
                        success: function(f, a){
                            
                            //TODO: this is not the best way to access the containers...
                            tab.ownerCt.grid.reload();
                            tab.ownerCt.remove(tab);
                        },
                        failure: function(f, a){
                            Ext.MessageBox.alert("Failure","Article not created due to some spurious problems");
                            f.markInvalid(a.result.errors);
                        }
                    });
                }
            },{
                text: 'Cancel',
                handler: function(){
                    //TODO: Check whether this is the right way
                    //to close a tab
                    var ct = tab.ownerCt;
                    ct.remove(tab);
                }
            }],
            items: [{
                xtype:'textfield',
                fieldLabel: 'Title',
                name: 'title',
                id:'text-title',
                anchor:'95%'
            },{
                xtype:'myhtmleditor',
                id: newid,
                enableMarking: true,
                fieldLabel:'Content',
                name: 'content',
                height:300,
                anchor:'98%'
            }]
    
        });
        this.add(tab);
        this.setActiveTab(tab);
    },
    
    deleteArticle: function() {
    	var data = this.gsm.getSelected().data;
    	var deleteid = data.id;
    	new Ext.data.Connection().request({
            url: 'DeleteArticle',
            params: {id: deleteid},
            method: 'POST',
            scope: this,
            failure: function(response, options){
                Ext.example.msg('Failure', 'Article deleted unsuccessfully');
            },
            success: function(response, options){
                Ext.example.msg('Success', 'Article id ' + deleteid + ' deleted successfully');
                this.grid.reload();
            }                
        });
    },
    editArticle: function() {
        var newid = 'contenteditor'+Ext.id();
        
        var tab = new Ext.FormPanel({
            id: 'my-details',
            labelAlign: 'top',
            frame:true,
            title: 'Edit Article',
            bodyStyle:'padding:5px 5px 0',
            width: 600,
            closable:true,
            
            
            buttons: [{
                text: 'Save',
                type: 'submit',
                scope: this,
                handler: function(){
                    tab.getForm().submit({
                        url:'UpdateArticle',
                        waitMsg:'Saving Article...',
                        success: function(f, a){
                            
                            //TODO: this is not the best way to access the containers...
                            tab.ownerCt.grid.reload();
                            tab.ownerCt.remove(tab);
                        },
                        failure: function(f, a){
                            Ext.MessageBox.alert("Failure","Article not updated due to some spurious problems");
                            f.markInvalid(a.result.errors);
                        }
                    });
                }
            },{
                text: 'Cancel',
                handler: function(){
                    //TODO: Check whether this is the right way
                    //to close a tab
                    var ct = tab.ownerCt;
                    ct.remove(tab);
                }
            }],
            
            items: [{
                xtype:'textfield',
                fieldLabel: 'Id',
                name: 'id',
                id:'text-id-edit',
                anchor:'95%'
            },{
                xtype:'textfield',
                fieldLabel: 'Title',
                name: 'title',
                id:'text-title-edit',
                anchor:'95%'
            },{
                xtype:'myhtmleditor',
                id: newid,
                enableMarking: true,
                fieldLabel:'Content',
                name: 'content',
                height:300,
                anchor:'98%'
            }]
    
        });
        var data = this.gsm.getSelected().data;
        Ext.getCmp('text-title-edit').setValue(data.title);
        Ext.getCmp('text-id-edit').setValue(data.id);
        Ext.getCmp(newid).setValue(data.content);
        
        
        this.add(tab);
        this.setActiveTab(tab);
    }
});